package com.wtp.wallpaper.task;

import com.wtp.wallpaper.annotation.ScheduledAnnotation;
import com.wtp.wallpaper.pojo.entity.Picture;
import com.wtp.wallpaper.pojo.entity.ScoreSum;
import com.wtp.wallpaper.service.PictureService;
import com.wtp.wallpaper.service.ScoreSumService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;
import java.util.Set;

@Slf4j
@Component
@ScheduledAnnotation(value = "处理用户评分",
        cron = "0 0 0/1 * * ?",
        description = "该定时任务用于处理用户对图片的评分，一小时执行一次")
public class RatingTask implements Runnable{

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SimpleMessageListenerContainer messageListenerContainer;

    @Autowired
    private ScoreSumService scoreSumService;

    @Autowired
    private PictureService pictureService;


    // 定时任务，每10分钟执行一次
    //@Scheduled(fixedRate = 600000)  // 每10分钟执行
    public void processRatings() {
        log.info("开始处理评分数据");
        // 1. 暂停 RabbitMQ 消费者
        stopConsumer();

        // 2. 处理 Redis 中的评分数据
        processRatingsFromRedis();

        // 3. 恢复 RabbitMQ 消费者
        startConsumer();
        log.info("处理评分数据完成");
    }

    // 暂停 RabbitMQ 消费者
    private void stopConsumer() {
        messageListenerContainer.stop();
    }

    // 恢复 RabbitMQ 消费者
    private void startConsumer() {
        messageListenerContainer.start();
    }

    // 从 Redis 中获取并处理评分数据
    private void processRatingsFromRedis() {
        // 获取多个 壁纸的评分数据
        Set<String> wallpaperKeys = redisTemplate.keys("wallpaper:*:totalRating");
        if(wallpaperKeys == null || wallpaperKeys.isEmpty()){
            return;
        }
        log.info("定时任务处理:{}",wallpaperKeys);
        for (String key : wallpaperKeys) {
            String wallpaperId = key.split(":")[1];  // 从 key 中提取壁纸ID

            //新增评分总数
            float totalRating = Float.parseFloat(Objects.requireNonNull(redisTemplate.opsForValue().get(key)));

            //新增人数
            int ratingCount = Integer.parseInt(Objects.requireNonNull(redisTemplate.opsForValue().get("wallpaper:" + wallpaperId + ":ratingCount")));

            //更新评分的人数和总分
            ScoreSum scoreSum = scoreSumService.lambdaQuery()
                    .eq(ScoreSum::getPicId, wallpaperId)
                    .one();
            if(scoreSum == null){
                scoreSum = new ScoreSum();
                //设置壁纸id
                scoreSum.setPicId(Long.valueOf(wallpaperId));
            }
            scoreSum.setScoreSum(scoreSum.getScoreSum() + totalRating);
            scoreSum.setScoreNum(scoreSum.getScoreNum() + ratingCount);
            scoreSumService.saveOrUpdate(scoreSum);

            //更新图片的评分
            double averageRating = (double) scoreSum.getScoreSum() / scoreSum.getScoreNum();
            BigDecimal score = new BigDecimal(averageRating).setScale(1, RoundingMode.HALF_UP);
            pictureService.lambdaUpdate()
                    .eq(Picture::getId,wallpaperId)
                    .set(Picture::getScore,score)
                    .update();
        }
        //处理完后清除壁纸缓存
        redisTemplate.delete(wallpaperKeys);
    }

    @Override
    public void run() {
        processRatings();
    }
}

